package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.Result;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exception.EduException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author zr
 * @since 2021-11-12
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    // 注入远程调用的方法
    @Autowired
    private VodClient vodClient;

    // 根据课程Id删除小节 首先删除视频 再删除小节
    // TOOD 删除小节时  删除对应的视频文件
    @Override
    public void removeVideoByCourseId(String courseId) {
        // 先得到所有的视频Id
        QueryWrapper<EduVideo> videoQuery = new QueryWrapper<>();
        videoQuery.eq("course_id", courseId);
        // 查询指定的列
        videoQuery.select("video_source_id");
        List<EduVideo> eduVideos = baseMapper.selectList(videoQuery);
        // 遍历集合 得到List<String>
        List<String> videoIds = new ArrayList<>();
        for (int i = 0; i < eduVideos.size(); i++) {
            // 得到每个对象
            EduVideo eduVideo = eduVideos.get(i);
            // 取出每个Id
            String videoSourceId = eduVideo.getVideoSourceId();
            // 进行判空
            if (StringUtils.hasText(videoSourceId)) {
                videoIds.add(videoSourceId);
            }
        }
        // 对集合进行判空
        if (videoIds.size() > 0) {
            // 删除多个视频
            vodClient.removeBatchAliYunVideos(videoIds);
        }
        // 按照条件进行删除
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        baseMapper.delete(queryWrapper);
    }

    /**
     * 删除小节时 删除对应的阿里云视频
     *
     * @param videoId
     * @return
     */
    @Override
    public boolean deleteVideoByVideoId(String videoId) {
        // 首先根据小节Id查询到小节
        EduVideo eduVideo = baseMapper.selectById(videoId);
        // 根据查询到的eduVideo找到对应的视频Id
        String videoSourceId = eduVideo.getVideoSourceId();
        // 判断videoSourceId是否为空 不为空再进行删除视频
        if (StringUtils.hasText(videoSourceId)) {
            // 远程调用删除视频
            Result result = vodClient.removeAliYunVideo(videoSourceId);
            // 测试熔断器效果 TOOD
            if (result.getCode().equals(20001)){
                throw new EduException("删除视频失败",20001);
            }
        }
        // 最后删除小节
        int result = baseMapper.deleteById(videoId);
        return result > 0;
    }
}
